import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.hamcrest.core.SubstringMatcher;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

@Getter
@Setter
@Data
public class ChatUI{
    JPanel contentPane;
    JTextField inputArea;
    JTextArea recordPane;
    JFrame frame;
    String msg;
    boolean connected_status = false;
    ObjectOutputStream oos;
    ObjectInputStream ois;
    ChatClient client;
    Socket socket;


    public ChatUI(final ChatClient client, final Socket socket) {
        this.client = client;
        this.socket = socket;
        System.out.println(socket);
        frame=new JFrame("多人聊天室");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(500, 150, 860, 450);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        frame.setContentPane(contentPane);
        contentPane.setLayout(null);

        //聊天记录面板
        recordPane = new JTextArea();
        recordPane.setFont(new Font("宋体",Font.BOLD,16));
        recordPane.setBounds(25, 9, 800, 250);
        contentPane.add(recordPane);

        //输入框
        inputArea = new JTextField();
        inputArea.setFont(new Font("宋体",Font.BOLD,16));
        inputArea.setBounds(25, 300, 650, 69);
        contentPane.add(inputArea);
        inputArea.setColumns(10);
        frame.setVisible(true);
        inputArea.setText("请输入您的昵称：" + "\n");

        //发送按钮
        JButton btnSend = new JButton("发送");
        btnSend.addActionListener(new ActionListener() {
            @Override
            @SneakyThrows
            public void actionPerformed(ActionEvent arg0) {
                msg = inputArea.getText();
                if(msg.startsWith("请输入您的昵称：")) {
                    msg = msg.substring(8);
                }
//                recordPane.append(msg + "\n");
                while (!connected_status) {
                    try {
                        oos = new ObjectOutputStream(socket.getOutputStream());
                        ois = new ObjectInputStream(socket.getInputStream());
                        connected_status = true;
                        new Thread(new ClientRecv(client, ois, recordPane)).start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                每次点击发送按钮，发送消息
                oos.writeObject(msg);
                oos.flush();
//                发送完清空输入栏
                inputArea.setText("");
            }
        });
        btnSend.setBounds(700, 300, 100, 69);
        contentPane.add(btnSend);
    }
}